package dbzx.pdf;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class AddingPageNumberXtoY {
	 public static final String SRC = "E:/项目资料/pdfCreat/1571736040633.pdf";
	    public static final String DEST = "E:/项目资料/pdfCreat/";

	    public static void main(String[] args) throws IOException, DocumentException {
	    	String destPath = DEST + String.valueOf(System.currentTimeMillis()) +"Copy.pdf";
	        File file = new File(destPath);
	        file.getParentFile().mkdirs();
	        new AddingPageNumberXtoY().manipulatePdf(SRC, destPath);
	        System.out.println("已生成页码！！！！");
	    }

	    public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
	        PdfReader reader = new PdfReader(src);
	        int n = reader.getNumberOfPages();
	        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
	        PdfContentByte pagecontent;
	        for (int i = 0; i < n; ) {
	            pagecontent = stamper.getOverContent(++i);
	            ColumnText.showTextAligned(pagecontent, Element.ALIGN_RIGHT,
	                    new Phrase(String.format("%s/%s", i, n)), 559, 806, 0);
	        }
	        stamper.close();
	        reader.close();
	    }
}
